﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;

namespace IntraVision.Web
{
    public class SqlExceptionHelper
    {
        public static string Language { get { return System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; } }

        public static Exception WrapException(SqlException ex)
        {
            XmlDocument doc = new XmlDocument();
            if (!string.IsNullOrEmpty(Language) && File.Exists(HttpContext.Current.Server.MapPath(String.Format("customsqlerrors-{0}.xml", Language))))
                doc.Load(HttpContext.Current.Server.MapPath(String.Format("customsqlerrors-{0}.xml", Language)));
            else if (File.Exists(HttpContext.Current.Server.MapPath("customsqlerrors.xml")))
                doc.Load(HttpContext.Current.Server.MapPath("customsqlerrors.xml"));

            foreach (System.Xml.XmlElement node in doc.SelectNodes("errors/error"))
            {
                if (node.HasAttribute("key") && !string.IsNullOrEmpty(node.Attributes["key"].Value))
                {
                    string key = node.Attributes["key"].Value.ToLower();
                    if (ex.Message.ToLower().Contains(key))
                        return new Exception(ReplaceMacroses(node.InnerText));
                }
            }
            return ex;
        }

        private static string ReplaceMacroses(string text)
        {
            return text.Replace("@getdate", DateTime.Now.ToShortDateString());
        }
    }
}
